package com.pzhu.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pzhu.common.constant.ErrorCode;
import com.pzhu.model.entity.User;
import com.pzhu.model.help.ResponseResult;
import com.pzhu.service.UserService;
import com.pzhu.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @Author : zqh
 * @Date : 2023/11/28 0028 下午 7:16
 * @Version: 1.0
 */
@Slf4j
@Api(tags = "小程序用户相关接口")
@RestController
@RequestMapping("/wx/user")
public class WxUserController {

    @Value("${mini.appid}")
    private String appid;

    @Value("${mini.secret}")
    private String secret;

    @Autowired
    private UserService userService;

    @ApiOperation("微信小程序登录")
    @GetMapping("/login")
    public ResponseResult login(String code) throws IOException {
        if (StringUtil.isEmpty(code)) {
            return ResponseResult.error(ErrorCode.WX_LOGIN_ERR);
        }
        //创建一个请求对象
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //构建一个get请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?" + "appid=" +
                appid +
                "&secret=" +
                secret +
                "&js_code=" +
                code +
                "&grant_type=authorization_code";
        HttpGet get = new HttpGet(url);
        //发送请求
        CloseableHttpResponse response = client.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        log.info("请求响应码：{}",statusCode);

        String result = EntityUtils.toString(response.getEntity());

        log.info("请求结果:-->{}",result);

        JSONObject jsonObject = JSON.parseObject(result);

        String openid = jsonObject.getString("openid");
        log.info("微信小程序的唯一标识：{}",openid);
        //根据openid查询用户信息 是否存在 不存在则插入一条数据
        return userService.miniLogin(openid);
    }

    @ApiOperation("更新用户信息")
    @PostMapping("/update/info")
    public ResponseResult updateInfo(@RequestBody User user) {
        return userService.updateByOPenId(user);
    }
}
